package com.cat.greedyAlgorithm;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/reorganize-string/
 * @create 2025/10/12 14:39
 * @since JDK17
 */

public class Solution83 {
    public String reorganizeString(String s) {
        char[] arr = s.toCharArray();
        int n = s.length(), max = 0;
        int[][] h = new int[26][2];
        Arrays.setAll(h, i -> new int[2]);
        for (int i = 0; i < n; i++) { //
            int x = arr[i] - 'a';
            h[x][0] = x;
            h[x][1]++;
            max = Math.max(max, h[x][1]);
        }
        if (max > n / 2 + n % 2) {
            return "";
        }
        Arrays.sort(h, (a, b) -> b[1] - a[1]); // 按照频率排序
        for (int i = 0, x = 0; i < 2; i++) { //
            for (int j = i; j < n; j += 2) { //
                if (h[x][1] != 0) { //
                    arr[j] = ((char) (h[x][0] + 'a'));
                    h[x][1]--;
                } else {
                    x++;
                    j -= 2;
                }
            }
        }

        return new String(arr);
    }
}
